package com.qianheng.kit.base.operation;

import java.security.InvalidParameterException;

public abstract class AbstractOperationCheckerFactory {


    /* --------------  算子  --------------- */
    public static OperationChecker reverse(String msg, OperationChecker<OperationCheckContext> checker) {
        return new OperationChecker<OperationCheckContext>() {
            @Override
            public CheckResult check(OperationCheckContext checkContext) {
                CheckResult checkResult = checker.check(checkContext);
                boolean reverse = !(checkResult.isSuccess());
                return new CheckResult(reverse, msg + "->" + Boolean.toString(reverse) + "{" + checkResult.getReport() + "}");
            }
        };
    }

    public static OperationChecker allMatch(String msg, OperationChecker<OperationCheckContext>... checkers) {
        if (checkers == null || checkers.length == 0) {
            throw new InvalidParameterException("allMatch参数不能为空");
        }
        //为什么这些地方都不用Stream?  因为要输出日志.  如果使用 Arrays.stream(checkers).allMatch(...)  那么只能得到一个结果,不能处理日志
        //如果在.allMatch({...}) 里面使用方法体处理呢? 那么值保存在外面? 惰性求值可能引发问题.
        //都是匿名内部类, 太多的new, 会很影响性能?  还不如每个checker都实名, 单例注册bean ?  此处代码放一起反而不好,违背开闭原则.

        return new OperationChecker<OperationCheckContext>() {
            @Override
            public CheckResult check(OperationCheckContext checkContext) {
                CheckResult result = new CheckResult(true);
                for (OperationChecker<OperationCheckContext> checker : checkers) {
                    CheckResult checkResult = checker.check(checkContext);
                    if (!checkResult.isSuccess()) {
                        result.setSuccess(false);
                        result.setReport(new StringBuilder(msg + "->" + Boolean.toString(false) + "{" + checkResult.getReport() + "}"));
                        break;
                    }
                }
                return result;
            }
        };
    }

    public static OperationChecker anyMatch(String msg, OperationChecker<OperationCheckContext>... checkers) {
        if (checkers == null || checkers.length == 0) {
            throw new InvalidParameterException("allMatch参数不能为空");
        }
        return new OperationChecker<OperationCheckContext>() {
            @Override
            public CheckResult check(OperationCheckContext checkContext) {
                CheckResult result = new CheckResult(false);
                for (OperationChecker<OperationCheckContext> checker : checkers) {
                    CheckResult checkResult = checker.check(checkContext);
                    if (checkResult.isSuccess()) {
                        result.setSuccess(true);
                        result.setReport(new StringBuilder(msg + "->" + Boolean.toString(true) + "{" + checkResult.getReport() + "}"));
                        break;
                    }
                }
                return result;
            }
        };
    }

}
